package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Panicf("%s: %s", msg, err)
	}
}

func main() {
	// 连接到RabbitMQ服务器
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	// 创建通道
	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	// 声明队列
	q, err := ch.QueueDeclare(
		"hdyy", // 队列名称
		true,   // 持久化
		false,  // 不自动删除
		false,  // 非排他性
		false,  // 不等待
		nil,    // 参数
	)
	failOnError(err, "Failed to declare a queue")

	// 从命令行参数获取消息内容
	body := bodyFrom(os.Args)
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 发送消息到队列
	err = ch.PublishWithContext(ctx,
		"",     // 交换器，使用默认交换器
		q.Name, // 队列名称
		false,  // 不设置mandatory标志
		false,  // 不设置immediate标志
		amqp.Publishing{
			ContentType:  "application/json",
			Body:         []byte(body),
			DeliveryMode: amqp.Persistent, // 消息持久化
		})
	failOnError(err, "Failed to publish a message")
	log.Printf(" [x] Sent %s", body)
}

func bodyFrom(args []string) string {
	var s string
	if (len(args) < 2) || os.Args[1] == "" {
		s = "hello"
	} else {
		s = strings.Join(args[1:], " ")
	}
	s = fmt.Sprintf(`{
	"name":%s,,,
	}`, s)
	return s
}
